package com.upload.upload_module.manager.handler.upload;

import com.upload.upload_module.manager.request.UploadRequest;
import com.upload.upload_module.manager.response.UploadResponse;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;


@Service
public class UploadManager {

    public UploadResponse handler(UploadRequest uploadRequest) throws IOException {
        System.out.println(uploadRequest.getPath());
        String path = storeFile(uploadRequest);
        System.out.println(path);
        UploadResponse res = new UploadResponse();
        res.setMsg(path);
        return res;
    }

    private String storeFile(UploadRequest uploadRequest) throws IllegalStateException, IOException {
        // 获取原始文件名
        MultipartFile file = uploadRequest.getFile();
        String path = uploadRequest.getPath();
        try {
            String fileName = file.getOriginalFilename();
            byte[] bytes = file.getBytes();
            File filePath = new File(path + fileName);
            OutputStream out = new FileOutputStream(filePath);
            out.write(bytes);
            return filePath.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }
}
